package com.zlp.member.service.impl;

import com.zlp.common.base.BaseApiService;
import com.zlp.common.base.BaseResponse;
import com.zlp.common.constants.Constants;
import com.zlp.common.constants.Econstants;
import com.zlp.common.constants.Rconstants;
import com.zlp.common.core.token.GenerateToken;
import com.zlp.member.dao.UserDoMapper;
import com.zlp.member.entity.UserDo;
import com.zlp.member.service.QQAuthoriService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

@RestController
public class QQAuthoriServiceImpl extends BaseApiService<JSONObject> implements QQAuthoriService {
	@Autowired
	private UserDoMapper userMapper;
	@Autowired
	private GenerateToken generateToken;

	@Override
	public BaseResponse<JSONObject> findByOpenId(String qqOpenId) {
		// 1.根据qqOpenId查询用户信息
		if (StringUtils.isEmpty(qqOpenId)) {
			return setResultError("qqOpenId不能为空!");
		}
		// 2.如果没有查询到 直接返回状态码203
		Map<String, Object> paraMap = new HashMap<>();
		paraMap.put("qqOpenId",qqOpenId);
		UserDo userDo = userMapper.whereByBizKey(paraMap);
		if (userDo == null) {
			return setResultError(Econstants.HTTP_RES_CODE_NOTUSER_203, "根据qqOpenId没有查询到用户信息");
		}
		// 3.如果能够查询到用户信息的话 返回对应用户信息token
		String keyPrefix = Rconstants.MEMBER_TOKEN_KEYPREFIX + "QQ_LOGIN";
		String userId = userDo.getUserId();
		String userToken = generateToken.createToken(keyPrefix, userId + "");
		JSONObject data = new JSONObject();
		data.put("token", userToken);
		// 唯一登入
		// 1.获取cooke信息  删除redis
		// 2.查看sys_user_token 是否有用户登入信息 ，如果有在可用状态修改无效（1），在新增用户token信息
		// 3.事物一致性
		return setResultSuccess(data);
	}

}
